<template>
  <div>
    <el-dialog
      class="subject-status-add-record"
      :title="dialogTitle"
      width="700px"
      :show-close="true"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <div>
        <el-form :rules="rules" ref="formRef" size="mini" :model="formData" label-width="140px">
          <!-- ⭐1. 是否生效 -->
          <el-form-item label="是否生效：" prop="operation">
            <el-radio-group v-model="formData.operation" :disabled="allDisabled">
              <el-radio label="0">是</el-radio>
              <el-radio label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- ⭐2. 关联类型 -->
          <el-form-item label="关联类型：" prop="associationType">
            <el-radio-group v-model="formData.associationType" @change="handleRadioChange" :disabled="allDisabled">
              <el-radio label="1">本受试者</el-radio>
              <el-radio label="4">指定访视</el-radio>
              <el-radio label="6">全部访视</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- ⭐3. 目标访视 -->
          <el-form-item label="目标访视：" v-if="formData.associationType === '4'" prop="targetVisitId">
            <el-select
              v-model="formData.targetVisitId"
              placeholder="请选择"
              filterable
              clearable
              style="width: 75%"
              @change="handleTargetVisitChange($event)"
              :disabled="allDisabled"
            >
              <el-option
                v-for="item in sourceTableInterviewList"
                :key="item.id"
                :label="item.visitName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- ⭐4. 目标表 -->
          <el-form-item
            label="目标表："
            v-if="formData.associationType === '4' || formData.associationType === '6'"
            prop="targetTableId"
          >
            <el-select
              v-model="formData.targetTableId"
              placeholder="请选择"
              filterable
              clearable
              style="width: 75%"
              @change="handleTargetTableChange"
              :disabled="allDisabled"
            >
              <el-option
                v-for="item in targetTableOptions"
                :key="item.id"
                :label="item.tableName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- ⭐5. 目标变量 -->
          <el-form-item label="目标变量：" prop="targetVariableCrf">
            <el-select
              v-model="formData.targetVariableCrf"
              filterable
              clearable
              placeholder="请选择"
              style="width: 75%"
              :disabled="allDisabled"
              @change="handleTargetVariableChange"
            >
              <el-option
                v-for="item in targetVariableList"
                :key="item.variable"
                :label="item.variableName"
                :value="item.variable"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- ⭐6. 取值函数 -->
          <el-form-item label="取值函数：" prop="getterType">
            <el-select
              v-model="formData.getterType"
              filterable
              clearable
              placeholder="请选择"
              style="width: 75%"
              :disabled="allDisabled"
              @change="handleGetterTypeChange"
            >
              <el-option
                v-for="item in getterTypeList"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- ⭐7. 源表所在访视 -->
          <el-form-item label="源表所在访视：" prop="sourceVisitId" v-if="formData.associationType !== '6'">
            <el-select
              v-model="formData.sourceVisitId"
              placeholder="请选择"
              filterable
              clearable
              style="width: 75%"
              @change="handleSourceVisitChange($event)"
              :disabled="allDisabled"
            >
              <el-option
                v-for="item in sourceTableInterviewList"
                :key="item.id"
                :label="item.visitName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- ⭐8. 源表 -->
          <el-form-item label="源表：" prop="sourceTableId">
            <el-select
              v-model="formData.sourceTableId"
              placeholder="请选择"
              filterable
              clearable
              style="width: 75%"
              @change="handleSourceTableChange"
              :disabled="allDisabled"
            >
              <el-option
                v-for="item in sourceTableList"
                :key="item.id"
                :label="item.tableName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- ⭐9. 源表查询条件 -->
          <el-form-item label="源表查询条件：" prop="sourceCondition">
            <el-input
              style="width: 75%"
              type="textarea"
              :rows="2"
              clearable
              placeholder="请输入"
              v-model="formData.sourceCondition"
              disabled
            >
            </el-input>
            <el-button size="mini" style="margin-left: 4px" @click="handleSource" :disabled="allDisabled"
              >...</el-button
            >
          </el-form-item>
          <!-- 💭10. 函数参数 -->
          <el-form-item v-if="formData.getterType" label="函数参数：" prop="functionParameters">
            <!-- 🏀零类受试者状态 -->
            <template v-if="['1'].includes(formData.getterType)">
              <el-select
                v-model="formData.functionParameters"
                placeholder="请选择固定值"
                style="width: 75%"
                filterable
                clearable
                :disabled="allDisabled"
              >
                <el-option
                  v-for="item in functionParameterZeroOptions"
                  :key="item.codeValue"
                  :value="item.codeValue"
                  :label="item.statusName"
                ></el-option>
              </el-select>
            </template>
            <!-- 🏀一类源表变量 -->
            <template v-if="['2', '3'].includes(formData.getterType)">
              <el-select
                v-model="formData.functionParameters"
                placeholder="请选择源表中的变量"
                style="width: 75%"
                filterable
                clearable
                :disabled="allDisabled"
              >
                <el-option
                  v-for="item in functionParameterOneOptions"
                  :key="item.variable"
                  :value="item.variable"
                  :label="item.variableName"
                ></el-option>
              </el-select>
            </template>
            <!-- 🏀二类 表一表二变量一变量二 -->
            <template v-if="['4'].includes(formData.getterType)">
              <el-select
                style="width: 20%; margin-right: 3px"
                v-model="functionParameterTwo.tableOneValue"
                @change="handleTableOne"
                filterable
                clearable
                :disabled="allDisabled"
                placeholder="选择表1"
              >
                <el-option
                  v-for="item in functionParameterTwo.tableOneOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select
                style="width: 20%"
                v-model="functionParameterTwo.wordOneValue"
                :disabled="allDisabled"
                filterable
                clearable
                placeholder="选择变量1"
              >
                <el-option
                  v-for="item in functionParameterTwo.wordOneOptions"
                  :key="item.variable"
                  :value="item.variable"
                  :label="item.variableName"
                ></el-option>
              </el-select>
              -
              <el-select
                style="width: 20%; margin-right: 3px"
                v-model="functionParameterTwo.tableTwoValue"
                @change="handleTableTwo"
                :disabled="allDisabled"
                filterable
                clearable
                placeholder="选择表2"
              >
                <el-option
                  v-for="item in functionParameterTwo.tableTwoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select
                style="width: 20%"
                filterable
                clearable
                v-model="functionParameterTwo.wordTwoValue"
                :disabled="allDisabled"
                placeholder="选择变量2"
              >
                <el-option
                  v-for="item in functionParameterTwo.wordTwoOptions"
                  :key="item.variable"
                  :value="item.variable"
                  :label="item.variableName"
                ></el-option>
              </el-select>
            </template>
            <!-- 🏀三类 -->
            <template v-if="['5', '6', '7', '8', '9'].includes(formData.getterType)">
              <div v-for="(item, index) in functionParameterThreeColumns" :key="item.id" style="margin-bottom: 12px">
                <span>#</span>
                <span>{{ index + 1 }}</span>
                <span> = </span>
                <!-- 第一个访视 -->
                <el-select
                  @change="handleInterviewChange($event, index)"
                  placeholder="选择访视"
                  filterable
                  clearable
                  style="width: 20%; margin-right: 3px"
                  v-model="item.interview"
                  :disabled="allDisabled"
                >
                  <el-option
                    v-for="it in item.interviewOptions"
                    :key="it.id"
                    :label="it.visitName"
                    :value="it.id"
                  ></el-option>
                </el-select>
                <!-- 第二个表 -->
                <el-select
                  @change="handleTableChange($event, index)"
                  placeholder="选择表"
                  filterable
                  clearable
                  style="width: 20%; margin-right: 3px"
                  v-model="item.table"
                  :disabled="allDisabled"
                >
                  <el-option
                    v-for="it in item.tableOptions"
                    :key="it.id"
                    :label="it.tableName"
                    :value="it.id"
                  ></el-option>
                </el-select>
                <!-- 第三个变量 -->
                <el-select
                  placeholder="选择变量"
                  filterable
                  clearable
                  style="width: 20%; margin-right: 3px"
                  v-model="item.variable"
                  :disabled="allDisabled"
                >
                  <el-option
                    v-for="it in item.variableOptions"
                    :key="it.variable"
                    :label="it.variableName"
                    :value="it.variable"
                  >
                  </el-option>
                </el-select>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  round
                  @click="functionParameterDelete(item.id)"
                  :disabled="allDisabled"
                  >删除</el-button
                >
              </div>
              <el-button type="success" size="mini" round @click="functionParameterAdd()" :disabled="allDisabled"
                >+添加参数</el-button
              >
            </template>
          </el-form-item>
          <!-- 11. 自定义函数 -->
          <el-form-item v-if="['9'].includes(formData.getterType)" label="自定义函数：" prop="functionRule">
            <el-input
              style="width: 75%"
              :rows="2"
              clearable
              placeholder="请输入"
              :disabled="allDisabled"
              v-model="formData.functionRule"
            ></el-input>
            <p style="color: #999999">{{ this.customFunctionSpecificationTextOne }}</p>
            <p style="color: #999999">{{ this.customFunctionSpecificationTextTwo }}</p>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button size="small" type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 💭源表查询条件 -->
    <SourceTableQueryConditions
      :sourceTableQueryConditionsVisible.sync="sourceTableQueryConditionsVisible"
      :sourceTableQueryConditionsOptions="sourceTableQueryConditionsOptions"
      :sourceTableQueryConditionsOptionsEnums="sourceTableQueryConditionsOptionsEnums"
      :sourceTableList="sourceTableList"
      :formData="formData"
      @transmitString="transmitString"
      :surface="surface"
      :sourceConditionRemark="sourceConditionRemark"
    ></SourceTableQueryConditions>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import { getterTypeList, defaultFormData, functionParameterTwo } from '../data'
import SourceTableQueryConditions from './source-table-query-conditions'
import { generateRandomId } from '@/utils/modules/crossConLogic.js'
import { computed } from 'vue'

// 根据tableCode进行对象数组去重
const arrayOfObjectsRemoveDuplicates = arr => {
  const uniqueArr = arr.filter((obj, index, self) => {
    return self.findIndex(obj2 => obj2.tableCode === obj.tableCode) === index
  })
  return uniqueArr
}

export default {
  props: {
    editData: Object,
    dialogVisible: Boolean,
    dialogTitle: String,
    searchParams: Object,
    allDisabled: Boolean,
  },
  components: {
    SourceTableQueryConditions,
  },
  data() {
    return {
      // 源表查询条件弹窗
      sourceTableQueryConditionsVisible: false,
      rules: {
        operation: [{ required: true, message: '请输入', trigger: 'blur' }],
        associationType: [{ required: true, message: '请输入', trigger: 'blur' }],
        targetVisitId: [{ required: true, message: '请输入', trigger: 'blur' }],
        targetTableId: [{ required: true, message: '请输入', trigger: 'blur' }],
        targetVariableCrf: [{ required: true, message: '请输入', trigger: 'blur' }],
        getterType: [{ required: true, message: '请输入', trigger: 'blur' }],
        functionRule: [{ required: true, message: '请输入', trigger: 'blur' }],
        functionParameters: [{ validator: this.validatorFunctionParameters }],
      },
      // 默认表格数据
      defaultFormData,
      formData: {},
      targetVariableList: [],
      getterTypeList,
      sourceTableInterviewList: [],
      sourceTableList: [],
      fieldList: [],
      projectId: '',
      databaseId: '',
      databaseVersion: '',
      databaseInfo: '',
      environment: '',
      // 💭源表查询条件开始
      sourceTableQueryConditionsOptions: [],
      sourceTableQueryConditionsOptionsEnums: {},
      // 💭源表查询条件结束
      // 函数参数开始
      functionParameterZeroOptions: [],
      functionParameterOneOptions: [],
      functionParameterTwo,
      functionParameterThreeColumns: [],
      // 函数参数结束
      targetTableOptions: [],
      customFunctionSpecificationTextOne: '支持运算： +，-，*，/，<，>，<=，>=，==，!=，%，++，--',
      customFunctionSpecificationTextTwo: '支持条件：in，like【类似sql语法】，&&，||，!，if then else等逻辑控制',
      surface: '',
      sourceConditionRemark: [],
    }
  },

  watch: {
    // 💭弹窗打开时，设置弹窗里面得数据
    async dialogVisible(val) {
      if (val) {
        // 获取源表所在访视&&目标访视
        this.getSourceTableInterviewList()
        // 新增的时候，表单项的数据清空；非新增的时候，回显表单项的值
        this.formData = this.editData.id ? { ...this.editData } : { ...this.defaultFormData }
        // 预览、复制
        if (this.editData.id) {
          // 取值函数为二类，设置回显
          if (['4'].includes(this.formData.getterType)) {
            this.functionParameterTwo = JSON.parse(this.formData.functionParametersRemark)
          }
          // 取值函数为三类，设置回显
          else if (['5', '6', '7', '8', '9'].includes(this.formData.getterType)) {
            this.functionParameterThreeColumns = JSON.parse(this.formData.functionParametersRemark)
          }
          // 设置源表查询条件表格
          if (this.editData.sourceConditionRemark) {
            this.sourceConditionRemark = JSON.parse(this.editData.sourceConditionRemark)
          }
        }

        // 🏀🏀🏀1 弹窗初始化，获取本受试者下
        if (this.formData.associationType === '1') {
          // 目标变量下拉项
          await this.getTargetVariableList('SUBJECT')
          // 如果是查看和复制
          if (this.editData.id) {
            // 获取源表下拉项
            const params = {
              ...this.searchParams,
              visitId: this.editData.sourceVisitId,
            }
            const res = await this.qrySourceTableList({ params })
            const { data, code } = res
            if (code === 200) {
              const uniqueArr = arrayOfObjectsRemoveDuplicates(data)

              // // 设置源表显示的名字优先取visitTableName
              // data.forEach(item => {
              //   if (item.visitTableName) {
              //     item.tableName = item.visitTableName
              //   }
              // })
              // 赋值源表下拉项
              this.sourceTableList = uniqueArr
            }

            // 获取源表查询条件的下拉项同时赋值函数参数
            if (this.editData.sourceTableId) {
              const id = this.editData.sourceTableId
              //  💭
              const obj = this.sourceTableList.find(item => item.id === id)
              const value = obj.tableCode
              // 获取源表查询条件的下拉项
              this.surface = value
              const params = {
                ...this.searchParams,
                surface: value,
              }
              this.qryVariableConfigListNoLoading({ params }).then(res => {
                const { data, code } = res
                if (code === 200) {
                  this.fieldList = data
                  // 源表查询条件下拉项
                  this.sourceTableQueryConditionsOptions = data
                  // 设置源表查询条件下拉项enums
                  data.forEach(item => {
                    this.sourceTableQueryConditionsOptionsEnums[item.variable] = item.variableName
                  })

                  // 🏀函数参数一类下拉项
                  this.functionParameterOneOptions = data

                  // 🏀函数参数二类下拉项
                  const arr = []
                  // 如果选择了目标表，添加目标表
                  if (this.formData.targetTableId && this.formData.targetTableId !== '-1') {
                    const objOfTarget = this.targetTableOptions.find(item => item.id === this.formData.targetTableId)
                    if (objOfTarget.tableCode !== objOfSource.tableCode) {
                      arr.push({
                        label: objOfTarget.tableName,
                        value: objOfTarget.tableCode,
                      })
                    }
                  }
                  arr.push({
                    label: obj.tableName,
                    value: obj.tableCode,
                  })
                  if (this.formData.associationType === '1') {
                    if (arr[0].value !== 'SUBJECT') {
                      arr.push({
                        label: '受试者信息',
                        value: 'SUBJECT',
                      })
                    }
                  }
                  this.functionParameterTwo.tableOneOptions = arr
                  this.functionParameterTwo.tableTwoOptions = arr
                }
              })
            }
          }
          // 如果取值函数是前三类，设置把函数参数中文换成英文
          // 取值函数为等于固定值&&目标变量为受试者状态
          if (this.editData.targetVariableCrf === 'STATUS' && this.editData.getterType === '1') {
            const params = {
              projectId: this.projectId,
            }
            const res = await this.qryProjectSubjectStatusList({ params })
            this.functionParameterZeroOptions = res.data
            const obj = this.functionParameterZeroOptions.find(
              item => item.statusName === this.editData.functionParameters
            )
            this.formData.functionParameters = obj.codeValue
          }
          // 取值函数为等于或者当前年龄
          if (['2', '3'].includes(this.editData.getterType)) {
            const objOfSource = this.sourceTableList.find(item => item.id === this.editData.sourceTableId)
            const value = objOfSource.tableCode
            // 获取源表查询条件的下拉项
            this.surface = value
            const params = {
              ...this.searchParams,
              surface: value,
            }

            const res = await this.qryVariableConfigListNoLoading({ params })
            const { data, code } = res
            if (code === 200) {
              this.fieldList = data
              // 源表查询条件下拉项
              this.sourceTableQueryConditionsOptions = data
              // 设置源表查询条件下拉项enums
              data.forEach(item => {
                this.sourceTableQueryConditionsOptionsEnums[item.variable] = item.variableName
              })
              // 🏀函数参数一类下拉项
              this.functionParameterOneOptions = data
              const obj = this.functionParameterOneOptions.find(
                item => item.variableName === this.editData.functionParameters
              )
              this.formData.functionParameters = obj.variable
            }
          }
        }

        // 4. 🏀🏀🏀弹窗初始化，获取指定访视下 目标表下拉项&原表下拉项
        else if (this.formData.associationType === '4' && this.editData.id) {
          // 1. 目标表下拉项
          const paramsOne = {
            ...this.searchParams,
            visitId: this.editData.targetVisitId,
          }
          const resOne = await this.qrySourceTableList({ params: paramsOne })
          if (resOne.code === 200) {
            this.targetTableOptions = resOne.data
          }

          // 2. 源表下拉项
          const paramsTwo = {
            ...this.searchParams,
            visitId: this.editData.sourceVisitId,
          }
          const resTwo = await this.qrySourceTableList({ params: paramsTwo })
          if (resTwo.code === 200) {
            // resTwo.data.forEach(item => {
            //   if (item.visitTableName) {
            //     item.tableName = item.visitTableName
            //   }
            // })

            const uniqueArr = arrayOfObjectsRemoveDuplicates(resTwo.data)
            this.sourceTableList = uniqueArr
          }

          // 获取目标变量下拉项
          this.handleTargetTableChange(this.editData.targetTableId)
          // 获取源表查询条件的下拉项
          if (this.editData.sourceTableId) {
            const id = this.editData.sourceTableId

            const obj = this.sourceTableList.find(item => item.id === id)
            const value = obj.tableCode
            // 获取源表查询条件的下拉项
            this.surface = value
            const params = {
              ...this.searchParams,
              surface: value,
            }
            this.qryVariableConfigListNoLoading({ params }).then(res => {
              const { data, code } = res
              if (code === 200) {
                this.fieldList = data
                // 源表查询条件下拉项
                this.sourceTableQueryConditionsOptions = data
                // 设置源表查询条件下拉项enums
                data.forEach(item => {
                  this.sourceTableQueryConditionsOptionsEnums[item.variable] = item.variableName
                })

                // 🏀函数参数一类下拉项
                this.functionParameterOneOptions = data

                // 🏀函数参数二类下拉项
                const arr = []
                // 如果选择了目标表，添加目标表
                if (this.formData.targetTableId && this.formData.targetTableId !== '-1') {
                  const objOfTarget = this.targetTableOptions.find(item => item.id === this.formData.targetTableId)
                  if (objOfTarget.tableCode !== obj.tableCode)
                    arr.push({
                      label: objOfTarget.tableName,
                      value: objOfTarget.tableCode,
                    })
                }
                arr.push({
                  label: obj.tableName,
                  value: obj.tableCode,
                })
                if (this.formData.associationType === '1') {
                  if (arr[0].value !== 'SUBJECT') {
                    arr.push({
                      label: '受试者信息',
                      value: 'SUBJECT',
                    })
                  }
                }
                this.functionParameterTwo.tableOneOptions = arr
                this.functionParameterTwo.tableTwoOptions = arr
              }
            })
          }

          // 取值函数为等于或者当前年龄
          if (['2', '3'].includes(this.editData.getterType)) {
            const objOfSource = this.sourceTableList.find(item => item.id === this.editData.sourceTableId)

            const value = objOfSource.tableCode
            // 获取源表查询条件的下拉项
            this.surface = value
            const params = {
              ...this.searchParams,
              surface: value,
            }
            const res = await this.qryVariableConfigListNoLoading({ params })
            const { data, code } = res
            if (code === 200) {
              this.fieldList = data
              // 源表查询条件下拉项
              this.sourceTableQueryConditionsOptions = data
              // 设置源表查询条件下拉项enums
              data.forEach(item => {
                this.sourceTableQueryConditionsOptionsEnums[item.variable] = item.variableName
              })
              // 🏀函数参数一类下拉项
              this.functionParameterOneOptions = data
              const obj = this.functionParameterOneOptions.find(
                item => item.variableName === this.editData.functionParameters
              )
              this.formData.functionParameters = obj.variable
            }
          }
        }

        // 6 🏀🏀🏀如果是查看&弹窗初始化，获取全部访视下 目标表和源表下拉项
        else if (this.formData.associationType === '6' && this.editData.id) {
          const params = {
            ...this.searchParams,
          }
          // const res = await this.qryDesignList({ params })
          // res.data.forEach(item => {
          //   item.tableName = item.surfaceName
          //   item.tableCode = item.surface
          // })
          const res = await this.visitTableList({ params })
          if (res.code === 200) {
            // // 设置源表显示的名字优先取visitTableName
            // res.data.forEach(item => {
            //   if (item.visitTableName) {
            //     item.tableName = item.visitTableName
            //   }
            // })
            const uniqueArr = arrayOfObjectsRemoveDuplicates(res.data)
            //目标表下拉项
            this.targetTableOptions = uniqueArr
            // 源表下拉项
            this.sourceTableList = uniqueArr
          }

          // 获取目标变量下拉项
          this.handleTargetTableChange(this.editData.targetTableId)

          // 如果选择了源表，获取源表查询条件内部的下拉项
          if (this.editData.sourceTableId) {
            const id = this.editData.sourceTableId

            const obj = this.sourceTableList.find(item => item.id === id)
            const value = obj.tableCode
            // 获取源表查询条件的下拉项
            this.surface = value
            const params = {
              ...this.searchParams,
              surface: value,
            }
            this.qryVariableConfigListNoLoading({ params }).then(res => {
              const { data, code } = res
              if (code === 200) {
                this.fieldList = data
                // 源表查询条件下拉项
                this.sourceTableQueryConditionsOptions = data
                // 设置源表查询条件下拉项enums
                data.forEach(item => {
                  this.sourceTableQueryConditionsOptionsEnums[item.variable] = item.variableName
                })

                // 🏀函数参数一类下拉项
                this.functionParameterOneOptions = data

                // 🏀函数参数二类下拉项
                const arr = []
                // 如果选择了目标表，添加目标表
                if (this.formData.targetTableId && this.formData.targetTableId !== '-1') {
                  const objOfTarget = this.targetTableOptions.find(item => item.id === this.formData.targetTableId)
                  if (objOfTarget.tableCode !== obj.tableCode) {
                    arr.push({
                      label: objOfTarget.tableName,
                      value: objOfTarget.tableCode,
                    })
                  }
                }
                arr.push({
                  label: obj.tableName,
                  value: obj.tableCode,
                })
                if (this.formData.associationType === '1') {
                  if (arr[0].value !== 'SUBJECT') {
                    arr.push({
                      label: '受试者信息',
                      value: 'SUBJECT',
                    })
                  }
                }
                this.functionParameterTwo.tableOneOptions = arr
                this.functionParameterTwo.tableTwoOptions = arr
              }
            })
          }
          // 取值函数为等于或者当前年龄
          if (['2', '3'].includes(this.editData.getterType)) {
            const objOfSource = this.sourceTableList.find(item => item.id === this.editData.sourceTableId)
            const value = objOfSource.tableCode
            // 获取源表查询条件的下拉项
            this.surface = value
            const params = {
              ...this.searchParams,
              surface: value,
            }
            const res = await this.qryVariableConfigListNoLoading({ params })
            const { data, code } = res
            if (code === 200) {
              this.fieldList = data
              // 源表查询条件下拉项
              this.sourceTableQueryConditionsOptions = data
              // 设置源表查询条件下拉项enums
              data.forEach(item => {
                this.sourceTableQueryConditionsOptionsEnums[item.variable] = item.variableName
              })
              // 🏀函数参数一类下拉项
              this.functionParameterOneOptions = data
              const obj = this.functionParameterOneOptions.find(
                item => item.variableName === this.editData.functionParameters
              )
              this.formData.functionParameters = obj.variable
            }
          }
        }
      } else {
        this.formData = { ...this.defaultFormData }
      }
    },
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    this.databaseId = this.databaseInfo.databaseId || ''
    this.databaseVersion = this.databaseInfo.databaseVersion || ''
    this.environment = sessionStorage.getItem('environment') || '0'
  },
  methods: {
    ...mapActions('eCRFDesign', [
      'addAutomatiValue',
      'editGeneralCoding',
      'qryVariableConfigListNoLoading',
      'qrySourceTableInterviewList',
      'qrySourceTableList',
      'qryDesignList',
    ]),
    ...mapActions('visitDesign', ['visitTableList']), // 全部访视，获取目标表和源表的下拉项
    ...mapActions('subjectStatus', ['qryProjectSubjectStatusList']),

    // 函数参数的自定义校验
    validatorFunctionParameters(rule, userList, callback) {
      if (['1'].includes(this.formData.getterType)) {
        if (this.formData.functionParameters) {
          callback()
        } else {
          callback(new Error('请填写完整！'))
        }
      } else if (['2', '3'].includes(this.formData.getterType)) {
        if (this.formData.functionParameters) {
          callback()
        } else {
          callback(new Error('请填写完整！'))
        }
      } else if (['4'].includes(this.formData.getterType)) {
        if (
          this.functionParameterTwo.tableOneValue &&
          this.functionParameterTwo.wordOneValue &&
          this.functionParameterTwo.tableTwoValue &&
          this.functionParameterTwo.wordTwoValue
        ) {
          callback()
        } else {
          callback(new Error('请填写完整！'))
        }
      } else if (['5', '6', '7', '8', '9'].includes(this.formData.getterType)) {
        let flag
        if (this.functionParameterThreeColumns.length === 0) {
          flag = false
        } else {
          flag = this.functionParameterThreeColumns.every(item => item.interview && item.table && item.variable)
        }
        if (flag) {
          callback()
        } else {
          callback(new Error('请填写完整！'))
        }
      }
    },

    // 获取受试者状态
    async getSubjectStateOptionsData() {
      const params = {
        projectId: this.projectId,
      }
      const res = await this.qryProjectSubjectStatusList({ params })
      this.functionParameterZeroOptions = res.data
    },

    // 查询目标变量下拉框选项
    getTargetVariableList(surface) {
      const params = {
        ...this.searchParams,
        surface,
      }
      this.qryVariableConfigListNoLoading({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.targetVariableList = data
        }
      })
    },

    // 获取源表所在访视&&目标访视
    getSourceTableInterviewList() {
      const params = {
        ...this.searchParams,
      }
      this.qrySourceTableInterviewList({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.sourceTableInterviewList = data
        }
      })
    },

    // 💭关联类型change
    async handleRadioChange(value) {
      const associationType = this.formData.associationType
      // 清除源表查询条件里面得数据
      if (value === '1') {
        this.getTargetVariableList('SUBJECT')
        this.formData = {
          ...this.defaultFormData,
        }
        // 源表清空
        this.sourceTableList = []
      }
      if (value === '4') {
        this.formData = {
          ...this.defaultFormData,
        }
        // 目标表清空
        this.targetTableOptions = []
        // 目标变量清空
        this.targetVariableList = []
        this.functionParameterZeroOptions = []
        // 源表清空
        this.sourceTableList = []
      }
      if (value === '6') {
        this.formData = {
          ...this.defaultFormData,
        }
        // 获取全部访视下的目标表和源表
        const params = {
          ...this.searchParams,
        }
        // const res = await this.qryDesignList({ params })
        // res.data.forEach(item => {
        //   item.tableName = item.surfaceName
        //   item.tableCode = item.surface
        // })
        const res = await this.visitTableList({ params })
        if (res.code === 200) {
          // // 设置源表显示的名字优先取visitTableName
          // res.data.forEach(item => {
          //   if (item.visitTableName) {
          //     item.tableName = item.visitTableName
          //   }
          // })
          const uniqueArr = arrayOfObjectsRemoveDuplicates(res.data)
          this.targetTableOptions = uniqueArr
          this.sourceTableList = uniqueArr
        }
      }

      this.formData.associationType = associationType
    },

    // 💭目标访视change
    async handleTargetVisitChange(value) {
      // 获取目标表下拉项
      const params = {
        ...this.searchParams,
        visitId: value,
      }
      const res = await this.qrySourceTableList({ params })
      const { data, code } = res
      if (code === 200) {
        // // 设置源表显示的名字优先取visitTableName
        // data.forEach(item => {
        //   if (item.visitTableName) {
        //     item.tableName = item.visitTableName
        //   }
        // })
        // 目标表下拉项赋值
        const uniqueArr = arrayOfObjectsRemoveDuplicates(data)
        this.targetTableOptions = uniqueArr
        // 清空目标表值和目标变量值
        this.formData.targetTableId = ''
        this.targetVariableList = []
        this.formData.targetVariableCrf = ''
      }
    },
    // 💭目标表change
    handleTargetTableChange(id) {
      // 查询目标变量下拉框选项
      const obj = this.targetTableOptions.find(item => item.id === id)
      this.getTargetVariableList(obj.tableCode)
      // 🏀函数参数二类下拉项
      const arr = []
      // 如果选择了源表，添加源表
      if (this.formData.sourceTableId) {
        const objOfSource = this.sourceTableList.find(item => item.id === this.formData.sourceTableId)
        if (objOfSource.tableCode !== obj.tableCode) {
          arr.push({
            label: objOfSource.tableName,
            value: objOfSource.tableCode,
          })
        }
      }

      arr.push({
        label: obj.tableName,
        value: obj.tableCode,
      })

      this.functionParameterTwo.tableOneOptions = arr
      this.functionParameterTwo.tableTwoOptions = arr
    },

    // 💭目标变量change
    handleTargetVariableChange(val) {
      this.handleGetterTypeChange()
    },

    // 💭取值函数change
    handleGetterTypeChange() {
      if (this.formData.getterType === '1' && this.formData.targetVariableCrf === 'STATUS') {
        this.getSubjectStateOptionsData()
      } else {
        this.functionParameterZeroOptions = []
        this.formData.functionParameters = ''
      }
    },

    // 💭源表所在访视change
    async handleSourceVisitChange(value) {
      const params = {
        ...this.searchParams,
        visitId: value,
      }
      const res = await this.qrySourceTableList({ params })
      const { data, code } = res
      if (code === 200) {
        // // 设置源表显示的名字优先取visitTableName
        // data.forEach(item => {
        //   if (item.visitTableName) {
        //     item.tableName = item.visitTableName
        //   }
        // })
        // 赋值源表下拉项
        const uniqueArr = arrayOfObjectsRemoveDuplicates(data)
        this.sourceTableList = uniqueArr
        // 清空源表和源表查询条件和一类函数参数
        this.formData.sourceTableId = ''
        this.formData.sourceCondition = ''
        this.functionParameterOneOptions = []
        this.formData.functionParameters = ''
        // 清空源表查询条件
        this.sourceConditionRemark = []
        this.formData.sourceCondition = ''
        this.sourceTableQueryConditionsOptions = []
      }
    },

    // 💭 源表change
    async handleSourceTableChange(id) {
      const obj = this.sourceTableList.find(item => item.id === id)
      const value = obj.tableCode
      // 获取源表查询条件的下拉项
      this.surface = value
      const params = {
        ...this.searchParams,
        surface: value,
      }
      this.qryVariableConfigListNoLoading({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.fieldList = data
          // 源表查询条件下拉项
          this.sourceTableQueryConditionsOptions = data
          // 设置源表查询条件下拉项enums
          data.forEach(item => {
            this.sourceTableQueryConditionsOptionsEnums[item.variable] = item.variableName
          })

          // 🏀函数参数一类下拉项
          this.functionParameterOneOptions = data
          // 🏀函数参数二类下拉项
          const arr = []
          // 如果选择了目标表，添加目标表
          if (this.formData.targetTableId && this.formData.targetTableId !== '-1') {
            const objOfTarget = this.targetTableOptions.find(item => item.id === this.formData.targetTableId)
            // 如果已经选中的目标表和源表一样，则不添加目标表
            if (objOfTarget.tableCode !== obj.tableCode) {
              arr.push({
                label: objOfTarget.tableName,
                value: objOfTarget.tableCode,
              })
            }
          }
          arr.push({
            label: obj.tableName,
            value: obj.tableCode,
          })

          if (this.formData.associationType === '1') {
            if (arr[0].value !== 'SUBJECT') {
              arr.push({
                label: '受试者信息',
                value: 'SUBJECT',
              })
            }
          }

          this.functionParameterTwo.tableOneOptions = arr
          this.functionParameterTwo.tableTwoOptions = arr
        }
      })
      this.formData.functionParameters = ''
      this.functionParameterTwo = {
        tableOneValue: '',
        tableOneOptions: [],
        wordOneValue: '',
        wordOneOptions: [],
        tableTwoValue: '',
        tableTwoOptions: [],
        wordTwoValue: '',
        wordTwoOptions: [],
      }
      // 清空源表查询条件
      this.sourceConditionRemark = []
      this.formData.sourceCondition = ''
    },

    // 💭源表查询条件弹窗开始
    // 点击省略号
    handleSource() {
      this.sourceTableQueryConditionsVisible = true
    },
    // 接受拼接数据
    transmitString({ paramString, paramStringTwo, sourceColumns }) {
      this.formData.sourceCondition = paramString
      this.formData.sourceRule = paramStringTwo
      this.formData.sourceConditionRemark = JSON.stringify(sourceColumns)
    },
    // 💭源表查询条件弹窗结束

    // 💭函数参数开始
    // 第三类开始
    // 第一个选择
    handleInterviewChange(val, index) {
      const params = {
        ...this.searchParams,
        visitId: val,
      }
      this.qrySourceTableList({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.functionParameterThreeColumns[index].tableOptions = data
        }
      })
    },
    // 第二个选择
    async handleTableChange(val, index) {
      const obj = this.functionParameterThreeColumns[index].tableOptions.find(item => item.id === val)
      const params = {
        ...this.searchParams,
        surface: obj.tableCode,
      }
      const res = await this.qryVariableConfigListNoLoading({ params })
      if (res.code === 200) {
        this.functionParameterThreeColumns[index].variableOptions = res.data
      }
    },
    // 点击添加参数
    functionParameterAdd() {
      this.functionParameterThreeColumns.push({
        id: generateRandomId(),
        interview: '',
        interviewOptions: computed(() => {
          return this.sourceTableInterviewList
        }),
        table: '',
        tableOptions: [],
        variable: '',
        variableOptions: [],
      })
    },
    // 点击删除
    functionParameterDelete(id) {
      this.functionParameterThreeColumns = this.functionParameterThreeColumns.filter(item => item.id !== id)
    },
    // 第三类结束

    // 函数参数二类，第一个下拉项选择
    async handleTableOne(surface) {
      const params = {
        ...this.searchParams,
        surface,
      }
      const res = await this.qryVariableConfigListNoLoading({ params })
      this.functionParameterTwo.wordOneOptions = res.data
    },

    // 函数参数二类，第二个下拉项选择
    async handleTableTwo(surface) {
      const params = {
        ...this.searchParams,
        surface,
      }
      const res = await this.qryVariableConfigListNoLoading({ params })
      this.functionParameterTwo.wordTwoOptions = res.data
    },
    // 💭函数参数结束

    // 💭关闭取消
    handleClose(flag) {
      this.formData = { ...this.defaultFormData }
      this.$refs.formRef.resetFields()
      this.functionParameterThreeColumns = []
      this.functionParameterTwo = {
        tableOneValue: '',
        tableOneOptions: [],
        wordOneValue: '',
        wordOneOptions: [],
        tableTwoValue: '',
        tableTwoOptions: [],
        wordTwoValue: '',
        wordTwoOptions: [],
      }
      this.functionParameterZeroOptions = []
      this.functionParameterOneOptions = []
      // 目标访视和源表所在访视下拉项通用
      this.sourceTableInterviewList = []
      this.sourceTableList = []
      this.sourceConditionRemark = []
      if (flag === 'refresh') {
        this.$emit('handleCancel', 'refresh')
      } else {
        this.$emit('handleCancel')
      }
    },

    // 💭保存提交
    async handleSave() {
      // 预览
      if (this.dialogTitle === '查看') {
        this.handleClose()
        return
      }
      await this.$refs.formRef.validate()
      const data = {
        ...this.formData,
        ...this.searchParams,
      }
      // 🏀数据处理
      // ⭐目标访视
      if (data.targetVisitId) {
        data.targetVisit = this.sourceTableInterviewList.find(item => item.id === data.targetVisitId).visitName
      }
      // ⭐目标表
      if (data.targetTableId && data.targetTableId !== '-1') {
        const obj = this.targetTableOptions.find(item => item.id === data.targetTableId)
        data.targetTableCrf = obj.tableCode
        data.targetTable = obj.tableName
      }
      // ⭐目标变量
      if (data.targetVariableCrf) {
        const obj = this.targetVariableList.find(item => item.variable === data.targetVariableCrf)
        data.targetVariable = obj.variableName
      }
      // ⭐源表所在访视
      if (data.sourceVisitId) {
        const obj = this.sourceTableInterviewList.find(item => item.id === data.sourceVisitId)
        data.sourceVisit = obj.visitName
      }
      // ⭐源表
      if (data.sourceTableId) {
        const obj = this.sourceTableList.find(item => item.id === data.sourceTableId)
        data.sourceTable = obj.tableName
        data.sourceTableCrf = obj.tableCode
        // 给formData的sourceTableCrf设置编码名，用作源表查询条件的字段拼接
        this.formData.sourceTableCrf = obj.tableCode || ''
      }
      // 如果是本受试者下，手动赋值目标表
      if (data.associationType === '1') {
        data.targetTable = '受试者信息'
        data.targetTableCrf = 'SUBJECT'
        data.targetTableId = '-1'
      }
      // 改变environment
      data.environment = Number(data.environment)
      // 处理函数参数
      // ⭐
      if (['1'].includes(this.formData.getterType)) {
        if (this.formData.functionParameters) {
          data.functionParametersRemark = ''
          data.functionRule = this.formData.sourceTableCrf + '.' + data.functionParameters
          const obj = this.functionParameterZeroOptions.find(
            item => item.codeValue === this.formData.functionParameters
          )
          data.functionParameters = obj.statusName
        } else {
          data.functionParametersRemark = ''
          data.functionRule = ''
          data.functionParameters = ''
        }
      }
      // ⭐一类
      if (['2', '3'].includes(this.formData.getterType)) {
        data.functionParametersRemark = ''
        data.functionRule = this.formData.sourceTableCrf + '.' + data.functionParameters
        const obj = this.functionParameterOneOptions.find(item => item.variable === this.formData.functionParameters)
        data.functionParameters = obj.variableName
      }
      // ⭐二类
      if (['4'].includes(this.formData.getterType)) {
        const stringOne = this.functionParameterTwo.wordOneOptions.find(
          item => this.functionParameterTwo.wordOneValue === item.variable
        ).variableName
        const stringTwo = this.functionParameterTwo.wordTwoOptions.find(
          item => this.functionParameterTwo.wordTwoValue === item.variable
        ).variableName
        data.functionParameters = stringOne + ',' + stringTwo
        data.functionParametersRemark = JSON.stringify(this.functionParameterTwo)
        data.functionRule =
          this.formData.sourceTableCrf +
          '.' +
          this.functionParameterTwo.wordOneValue +
          ',' +
          this.formData.sourceTableCrf +
          '.' +
          this.functionParameterTwo.wordTwoValue
      }
      // ⭐三类
      if (['5', '6', '7', '8'].includes(this.formData.getterType)) {
        let stringParamOne = ''
        let stringParamTwo = ''
        this.functionParameterThreeColumns.forEach((item, index) => {
          if (index === 0) {
            stringParamOne =
              stringParamOne + item.variableOptions.find(it => it.variable === item.variable).variableName
            stringParamTwo = stringParamTwo + this.formData.sourceTableCrf + '.' + item.variable
          } else {
            stringParamOne =
              stringParamOne + ',' + item.variableOptions.find(it => it.variable === item.variable).variableName
            stringParamTwo = stringParamTwo + ',' + this.formData.sourceTableCrf + '.' + item.variable
          }
        })
        data.functionParameters = stringParamOne
        data.functionParametersRemark = JSON.stringify(this.functionParameterThreeColumns)
        data.functionRule = stringParamTwo
      }
      // 自定义函数
      if (['9'].includes(this.formData.getterType)) {
        let stringParamOne = ''
        this.functionParameterThreeColumns.forEach((item, index) => {
          if (index === 0) {
            stringParamOne =
              stringParamOne + item.variableOptions.find(it => it.variable === item.variable).variableName
          } else {
            stringParamOne =
              stringParamOne + ',' + item.variableOptions.find(it => it.variable === item.variable).variableName
          }
        })
        data.functionParameters = stringParamOne
        data.functionParametersRemark = JSON.stringify(this.functionParameterThreeColumns)
        data.functionRule = data.functionRule.replace(/\s+/g, '')
      }
      const res = await this.addAutomatiValue({
        data,
      })
      if (res.code === 200) {
        this.$message({
          message: '保存成功',
          type: 'success',
        })
        this.handleClose('refresh')
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.span-dropdown-item {
  display: inline-block;
  width: 120%;
}
</style>
